package com.example.demo.game;

import com.example.demo.model.Userinfo;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@Component
//管理对战房间的房间管理器
public class RoomManager {
    //管理房间Id和房间的映射
    private ConcurrentHashMap<String,Room> roomByRoomId =new ConcurrentHashMap<>();
    //管理用户id和房间的映射
    private ConcurrentHashMap<Integer,String> roomByUserId =new ConcurrentHashMap<>();
    //管理人机对战房间
    private ConcurrentHashMap<Integer,MachineRoom> MachineroomByUserId =new ConcurrentHashMap<>();
    /**
     * 增加房间
     * @param room
     * @param u
     * @param u2
     */
    public void add(Room room, Userinfo u,Userinfo u2) {
        System.out.println(room.getRoomId());
        roomByRoomId.put(room.getRoomId(),room);
        roomByUserId.put(u.getUserid(),room.getRoomId());
        roomByUserId.put(u2.getUserid(),room.getRoomId());
        System.out.println("已将房间加入管理器");
    }

    /**
     * 新增人机对战房间
     * @param room
     * @param userinfo
     */
    public void addMachineRoom(MachineRoom room,Userinfo userinfo) {
        MachineroomByUserId.put(userinfo.getUserid(),room);
    }

    /**
     * 删除人机对战房间
     * @param roomid
     * @param u
     */
    public void removeMachineRoot(String roomid, Userinfo u) {
        roomByRoomId.remove(roomid);
        roomByUserId.remove(u.getUserid());
        System.out.println("已将房间移除管理器");
    }
    /**
     * 删除房间
     * @param
     * @param u
     * @param u2
     */
    public void remove(String roomid, Userinfo u, Userinfo u2) {
        roomByRoomId.remove(roomid);
        roomByUserId.remove(u.getUserid());
        roomByUserId.remove(u2.getUserid());
        System.out.println("已将房间移除管理器");
    }

    /**
     * 根据房间Id来返回房间
     * @return
     */
    public Room getRoomByRoomId(String roomId) {
        if(roomId==null) {
            System.out.println("匹配发生错误");
            return null;
        }
        return roomByRoomId.get(roomId);
    }

    /**
     * 根据用户的id来返回房间
     * @return
     */
    public Room getRoomByUserId(Integer userId) {
        if(userId==null) {
            System.out.println("匹配发生错误");
            return null;
        }
        String roomId= roomByUserId.get(userId);
        if(roomId==null) {
            System.out.println("此用户未匹配");
            return null;
        }
        return roomByRoomId.get(roomId);
    }
    public MachineRoom getMaRoomByUserId(Integer userId) {
        if(userId==null) {
            System.out.println("匹配发生错误");
            return null;
        }

        return MachineroomByUserId.get(userId);
    }
}
